﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace LFramework.Data
{
    /// <summary>
    /// 数据库连接字符串生成
    /// </summary>
    public static class ConnectionStringBuilder
    {
        /// <summary>
        /// 生成SqlServer连接字符串
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static string BuildSqlServerConnectionString(DataSourceInfo ds)
        {
            string connStr = "Server=" + ds.IP + " ;UID =" + ds.UID + " ;Pwd=" + ds.PWD + " ;Connection Timeout=" + ds.ConnTimeout.ToString() + " ; ";

            if (!string.IsNullOrEmpty(ds.DbName)) connStr += "database=" + ds.DbName + ";";

            return connStr;
        }


        /// <summary>
        /// 生成Oracle连接字符串
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static string BuildOracleConnectionString(DataSourceInfo ds)
        {
            string connStr = "Data Source=" + ds.DbName + ";User Id=" + ds.UID + ";Password=" + ds.PWD + ";Connection Timeout=" + ds.ConnTimeout.ToString() + ";";

            return connStr;
        }





        /// <summary>
        /// 从配置文件读取连接字符串
        /// </summary>
        /// <returns>连接字符串</returns>
        public static string GetConnectionStringFromConfig(string name, out DbTypeEnum dbType)
        {
            try
            {
                ConnectionStringSettings css = ConfigurationManager.ConnectionStrings[name];

                switch (css.ProviderName.ToLower())
                {
                    case "sqlserver":
                        dbType = DbTypeEnum.SqlServer;
                        break;
                    case "access":
                        dbType = DbTypeEnum.Access;
                        break;
                    case "oracle":
                        dbType = DbTypeEnum.Oracle;
                        break;
                    default:
                        throw new Exception("未知的ProviderName：" + css.ProviderName);
                }

                return css.ConnectionString;
            }
            catch (Exception ex)
            {
                throw new Exception("读取配置文件连接字符串失败：" + Environment.NewLine + ex.Message);
            }
        }
    }
}
